/**
 * 操作数据的工具集
 */
/**
 *
 * @param { 目标对象 } targetObj
 * @param { 设置属性 } defaultProp
 * @param { 设置值 } value
 * @returns
 */
export function setDefaultProp(targetObj, defaultProp, value) {
  return (targetObj[defaultProp] = value)
}

export function proxyData() {
  return {
    set: function(recObj, key, value) {
      console.log(key, 'is changed to', value) // name is changed to lisi
      recObj[key] = value
      return true
    }
  }
}

export class Observer {
  constructor(data) {
    console.log(data)
    // 遍历参数 data 的属性，给添加到 this 上
    for (const key of Object.keys(data)) {
      if (typeof data[key] === 'object') {
        data[key] = new Observer(data[key])
      }
      Object.defineProperty(this, key, {
        enumerable: true,
        configurable: true,
        get() {
          // console.log('你访问了' + key)
          return data[key]
        },
        set(newVal) {
          console.log('你设置了' + key)
          console.log('新的' + key + '=' + newVal)
          if (newVal === data[key]) {
            return
          }
          data[key] = newVal
        }
      })
    }
  }
}

export function deleteProps(obj, prop) {
  delete obj[prop]
}

export function dataWatch(data) {
  const keyList = {} // 被监听的数据列表
  const objHandler = {
    get: function(target, propKey) {
      return target[propKey]
    },
    set: function(target, propKey, value) {
      if (Object.keys(keyList).indexOf(propKey) > -1) {
        keyList[propKey](value)
      }
      console.log(value)
      target[propKey] = value
      return true
    }
  }
  const objProxy = new Proxy(data, objHandler)
  const operater = {
    setData: newData => {
      // 这里使用setTimeout把此循环放到堆栈的末尾执行 模拟异步效果
      setTimeout(() => {
        for (const key in newData) {
          if (newData.hasOwnProperty(key)) {
            objProxy[key] = newData[key] // 调用监听函数
          }
        }
      })
    },
    watch: function(key, callback) {
      keyList[key] = callback
    }
  }
  operater.setData(data)
  return operater
}
